<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\model\SettingModel;
use app\utils\ResData;

/**
 * 系统设置控制器
 */
class Setting
{
    // 使用检查登录、检查权限中间件
    protected $middleware = ['checklogin', 'checkpower'];


    /**
     * 网站设置视图页
     */
    public function index()
    {
        $itme = SettingModel::where('names', 'site_setting')->find();
        if ($itme) {
            $itme->values = json_decode($itme->values, true);
        }
        return view('setting/index', ['siteInfo' => $itme]);
    }


    /**
     * 保存提交数据
     */
    public function save()
    {
        $names = trim(input('post.names', ''));
        $values = json_encode(input('post.values', []), JSON_UNESCAPED_UNICODE);

        $itme = SettingModel::where('names', $names)->find();
        if (!$itme) {   // 记录不存在，进行新增
            $setting = new SettingModel();
            $setting->names = $names;
            $setting->values = $values;
            $res = $setting->save();
        } else {    // 记录存在，进行更新
            $itme->names = $names;
            $itme->values = $values;
            $res = $itme->save();
        }

        if (!$res) {
            return json(ResData::res(500, '操作失败'));
        }

        return json(ResData::res(200, '操作成功'));
    }
}